<template>
  <div>
    <div class="search-bar">
      <span class="label">年份</span>
      <el-date-picker
        size="mini"
        v-model="yearVal"
        type="year"
        :format="dateForm()"
        :value-format="dateForm()"
        placeholder="选择年"
        :clearable="false"
      >
      </el-date-picker>
      <span class="label">开始月份</span>
      <el-select v-model="startMonth" placeholder="请选择">
        <el-option
          size="mini"
          v-for="item in monthOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <span class="label">结束月份</span>
      <el-select v-model="endMonth" placeholder="请选择">
        <el-option
          size="mini"
          v-for="item in monthOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <el-button class="search-btn" size="mini" @click="toSearch"
        >查询</el-button
      >
      <el-button class="search-btn" size="mini" @click="toExport"
        >导出Excel</el-button
      >
    </div>
    <div class="table-title">机组完好率概况表</div>
    <el-table
      id="table"
      ref="table"
      :data="tableData"
      border
      style="width: 100%"
      :height="tableHeight"
      :row-style="rowStyle"
      class="el-table"
      :cell-style="rowStyle"
      :header-cell-style="rowStyle"
    >
      <el-table-column prop="index" label="序号" width="50"> </el-table-column>
      <el-table-column prop="deptName" label="部门" width="150">
      </el-table-column>
      <el-table-column prop="count" label="机组总数"> </el-table-column>
      <el-table-column prop="month1" label="1月"> </el-table-column>
      <el-table-column prop="month2" label="2月"> </el-table-column>
      <el-table-column prop="month3" label="3月"> </el-table-column>
      <el-table-column prop="month4" label="4月"> </el-table-column>
      <el-table-column prop="month5" label="5月"> </el-table-column>
      <el-table-column prop="month6" label="6月"> </el-table-column>
      <el-table-column prop="month7" label="7月"> </el-table-column>
      <el-table-column prop="month8" label="8月"> </el-table-column>
      <el-table-column prop="month9" label="9月"> </el-table-column>
      <el-table-column prop="month10" label="10月"> </el-table-column>
      <el-table-column prop="month11" label="11月"> </el-table-column>
      <el-table-column prop="month12" label="12月"> </el-table-column>
      <el-table-column prop="quarter1" label="第一季度"> </el-table-column>
      <el-table-column prop="quarter2" label="第二季度"> </el-table-column>
      <el-table-column prop="quarter3" label="第三季度"> </el-table-column>
      <el-table-column prop="quarter4" label="第四季度"> </el-table-column>
      <el-table-column prop="halfYear" label="上半年"> </el-table-column>
      <el-table-column prop="year" label="年度"> </el-table-column>
    </el-table>
  </div>
</template>
<script>
import { detailsTable } from "@/api/operationManagement/runStatistical.js";
export default {
  data() {
    return {
      monthOptions: [
        {
          value: "1",
          label: "1",
        },
        {
          value: "2",
          label: "2",
        },
        {
          value: "3",
          label: "3",
        },
        {
          value: "4",
          label: "4",
        },
        {
          value: "5",
          label: "5",
        },
        {
          value: "6",
          label: "6",
        },
        {
          value: "7",
          label: "7",
        },
        {
          value: "8",
          label: "8",
        },
        {
          value: "9",
          label: "9",
        },
        {
          value: "10",
          label: "10",
        },
        {
          value: "11",
          label: "11",
        },
        {
          value: "12",
          label: "12",
        },
      ],
      yearVal: "",
      startMonth: "1",
      endMonth: "12",
      tableData: [],
      tableHeight: 0,
    };
  },
  created() {
    this.init();
  },
  mounted() {
    this.adjustSize();
    window.addEventListener("resize", this.adjustSize);
  },
  methods: {
    adjustSize() {
      this.$nextTick(() => {
        this.tableHeight =
          window.innerHeight - this.$refs.table.$el.offsetTop - 200;
        //window.innerHeight:浏览器的可用高度
        //this.$refs.table.$el.offsetTop：表格距离浏览器的高度
        //后面的50：根据需求空出的高度，自行调整
      });
    },
    init() {
      this.yearVal = new Date().getFullYear() + "";
      this.toSearch();
    },
    // 设置行颜色
    rowStyle({ row }) {
      let styleJson = {
        borderColor: "#000",
      };
      if (row.purple) {
        styleJson.background = "rgb(184,183,218)"; // 紫色
        return styleJson;
      } else if (row.yellow) {
        styleJson.background = "rgb(255,255,136)"; // 黄色
        return styleJson;
      } else {
        return styleJson;
      }
    },
    // 查询
    async toSearch() {
      let obj = {
        year: this.yearVal,
        startMonth: this.startMonth,
        endMonth: this.endMonth,
      };
      if (this.startMonth && this.endMonth && this.yearVal) {
        await detailsTable(obj).then((res) => {
          if (res.code == 200) {
            this.tableData = [];
            for (let index = 0; index < res.data.length - 1; index++) {
              let itemDep = res.data[index];
              let objDep = {
                purple: true,
                index: this.convertToChinaNum(index + 1),
                deptName: itemDep.deptName,
                count: itemDep.count,
                halfYear:
                  this.keepTwoDecimalFull(itemDep.halfYearItems.intactRate) +
                  "%",
                year:
                  this.keepTwoDecimalFull(itemDep.yearItems.intactRate) + "%",
              };
              for (let i = 1; i < 13; i++) {
                objDep["month" + i] =
                  this.keepTwoDecimalFull(
                    itemDep.monthItems[i - 1].intactRate
                  ) + "%";
              }
              for (let i = 1; i < 5; i++) {
                objDep["quarter" + i] =
                  this.keepTwoDecimalFull(
                    itemDep.quarterItems[i - 1].intactRate
                  ) + "%";
              }
              this.tableData.push(objDep);
              if (itemDep.unitDet.length) {
                itemDep.unitDet.forEach((item, index) => {
                  let obj = {
                    index: index + 1,
                    deptName: item.deptName,
                    count: item.count,
                    halfYear:
                      this.keepTwoDecimalFull(item.halfYearItems.intactRate) +
                      "%",
                    year:
                      this.keepTwoDecimalFull(item.yearItems.intactRate) + "%",
                  };
                  for (let i = 1; i < 13; i++) {
                    obj["month" + i] =
                      this.keepTwoDecimalFull(
                        item.monthItems[i - 1].intactRate
                      ) + "%";
                  }
                  for (let i = 1; i < 5; i++) {
                    obj["quarter" + i] =
                      this.keepTwoDecimalFull(
                        item.quarterItems[i - 1].intactRate
                      ) + "%";
                  }
                  this.tableData.push(obj);
                });
              }
            }
            let yearItem = res.data[res.data.length - 1];
            let yearObj = {
              yellow: true,
              index: this.convertToChinaNum(res.data.length),
              deptName: yearItem.deptName,
              count: yearItem.count,
              halfYear:
                this.keepTwoDecimalFull(yearItem.halfYearItems.intactRate) +
                "%",
              year:
                this.keepTwoDecimalFull(yearItem.yearItems.intactRate) + "%",
            };
            for (let i = 1; i < 13; i++) {
              yearObj["month" + i] =
                this.keepTwoDecimalFull(yearItem.monthItems[i - 1].intactRate) +
                "%";
            }
            for (let i = 1; i < 5; i++) {
              yearObj["quarter" + i] =
                this.keepTwoDecimalFull(
                  yearItem.quarterItems[i - 1].intactRate
                ) + "%";
            }
            this.tableData.push(yearObj);
          }
        });
      } else {
        this.$message.warning("年份、开始月份、结束月份均为必选项");
      }
    },
    // 四舍五入保留2位小数（不够位数，则用0替补）
    keepTwoDecimalFull(num) {
      let result = parseFloat(num);
      if (isNaN(result)) {
        // alert("传递参数错误，请检查！");
        // return false;
        return num;
      }
      result = Math.round(num * 100) / 100;
      let s_x = result.toString(); //将数字转换为字符串
      let pos_decimal = s_x.indexOf("."); //小数点的索引值
      // 当整数时，pos_decimal=-1 自动补0
      if (pos_decimal < 0) {
        pos_decimal = s_x.length;
        s_x += ".";
      }
      // 当数字的长度< 小数点索引+2时，补0
      while (s_x.length <= pos_decimal + 2) {
        s_x += "0";
      }
      if (s_x == "0.00") {
        return 0;
      } else if (s_x == "100.00") {
        return 100;
      } else {
        return s_x;
      }
    },
    // 导出Excel
    toExport() {
      let table = document.getElementById("table");
      let excelContent = table.innerHTML;
      let excelFile =
        "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:" +
        "excel" +
        "' xmlns='http://www.w3.org/TR/REC-html40'>";
      excelFile += "<>";
      excelFile += "<!--[if gte mso 9]>";
      excelFile += "<xml>";
      excelFile += "<x:ExcelWorkbook>";
      excelFile += "<x:ExcelWorksheets>";
      excelFile += "<x:ExcelWorksheet>";
      excelFile += "<x:Name>";
      excelFile += "{worksheet}";
      excelFile += "</x:Name>";
      excelFile += "<x:WorksheetOptions>";
      excelFile += "<x:DisplayGridlines/>";
      excelFile += "</x:WorksheetOptions>";
      excelFile += "</x:ExcelWorksheet>";
      excelFile += "</x:ExcelWorksheets>";
      excelFile += "</x:ExcelWorkbook>";
      excelFile += "</xml>";
      excelFile += "<![endif]-->";
      excelFile += "</head>";
      excelFile += "<body>";
      excelFile += excelContent;
      excelFile += "</body>";
      excelFile += "</html>";
      let base64data = "base64," + this.base64(excelFile);
      let fileName = "机组完好率概况表"; //下载的文件名称
      let prefix = "data:application/vnd.ms-excel;" + base64data;
      let a = document.createElement("a"); //创建a标签
      a.setAttribute("href", prefix);
      a.setAttribute("download", fileName);
      a.setAttribute("target", "_blank"); //打开一个新的窗口
      a.setAttribute("id", "downLoad");
      if (document.getElementById("downLoad")) {
        document.body.removeChild(document.getElementById("downLoad"));
      }
      document.body.appendChild(a);
      a.click();
    },
    base64(content) {
      return window.btoa(unescape(encodeURIComponent(content)));
    },
    //日期数据处理
    dateForm() {
      return "yyyy";
    },
    //将数字（整数）转为汉字，从零到一亿亿
    convertToChinaNum(num) {
      let arr1 = new Array(
        "零",
        "一",
        "二",
        "三",
        "四",
        "五",
        "六",
        "七",
        "八",
        "九"
      );
      let arr2 = new Array(
        "",
        "十",
        "百",
        "千",
        "万",
        "十",
        "百",
        "千",
        "亿",
        "十",
        "百",
        "千",
        "万",
        "十",
        "百",
        "千",
        "亿"
      ); //可继续追加更高位转换值
      if (!num || isNaN(num)) {
        return "零";
      }
      let english = num.toString().split("");
      let result = "";
      for (let i = 0; i < english.length; i++) {
        let des_i = english.length - 1 - i; //倒序排列设值
        result = arr2[i] + result;
        let arr1_index = english[des_i];
        result = arr1[arr1_index] + result;
      }
      //将【零千、零百】换成【零】 【十零】换成【十】
      result = result.replace(/零(千|百|十)/g, "零").replace(/十零/g, "十");
      //合并中间多个零为一个零
      result = result.replace(/零+/g, "零");
      //将【零亿】换成【亿】【零万】换成【万】
      result = result.replace(/零亿/g, "亿").replace(/零万/g, "万");
      //将【亿万】换成【亿】
      result = result.replace(/亿万/g, "亿");
      //移除末尾的零
      result = result.replace(/零+$/, "");
      //将【零一十】换成【零十】
      //result = result.replace(/零一十/g, '零十');//貌似正规读法是零一十
      //将【一十】换成【十】
      result = result.replace(/^一十/g, "十");
      return result;
    },
  },
};
</script>
<style lang="less" scoped>
.search-bar {
  text-align: left;
  .label {
    padding: 0 20px;
  }
  .label::before {
    content: "*";
    color: #f56c6c;
    margin-right: 4px;
  }
  .search-btn {
    margin-left: 20px;
  }
}
.table-title {
  font-size: 20px;
  font-weight: 600;
  margin-top: 10px;
}
.el-table {
  border: 1px solid #000;
}
/deep/ .el-table tr th {
  background-color: rgb(209, 227, 231);
}
/deep/ .el-table__body {
  border-bottom: 1px solid #000;
}
</style>